package com.atguigu.spzx.order.service.impl;

import com.atguigu.spzx.common.utils.AuthContextUtil;
import com.atguigu.spzx.feign.cart.CartFeignClient;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.feign.user.UserFeignClient;
import com.atguigu.spzx.model.dto.order.OrderInfoDto;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.order.OrderLog;
import com.atguigu.spzx.model.entity.product.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.entity.user.UserAddress;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.h5.TradeVo;
import com.atguigu.spzx.order.mapper.OrderInfoMapper;
import com.atguigu.spzx.order.mapper.OrderItemMapper;
import com.atguigu.spzx.order.mapper.OrderLogMapper;
import com.atguigu.spzx.order.service.OrderInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;



    @Override
    public TradeVo getTrade() {
        //需要获取购物车里的信息,封装到tradeVo里的集合里
        List<CartInfo> cartInfoList = cartFeignClient.getAllChecked();

        List<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {        // 将购物项数据转换成功订单明细数据
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItemList.add(orderItem);
        }

        // 计算总金额  大数的计算方式.
        BigDecimal totalAmount = new BigDecimal(0);
        for(OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        return tradeVo;
    }

    @Override
    public  Long  submitOrder(OrderInfoDto orderInfoDto) {
        //获取用户地址根据传过来的useraddressid  (user feign调用)
        Long userAddressId = orderInfoDto.getUserAddressId();
        UserAddress userAddress = userFeignClient.getUserAddressById(userAddressId);
        //插入订单信息order_info
        OrderInfo orderInfo = new OrderInfo();
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        orderInfo.setOrderNo("atguiguByYi"+String.valueOf(System.currentTimeMillis()));
        orderInfo.setUserId(userInfo.getId());
        orderInfo.setNickName(userInfo.getUsername());
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);
        orderInfo.setOrderStatus(0);
        orderInfoMapper.save(orderInfo);
        //插入订单详情信息 order_item
        Long orderInfoId= orderInfo.getId();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfoId);
            //检查库存是否超卖 (product feign 服务调用)
            ProductSku productSku=productFeignClient.getSkuById(orderItem.getSkuId());
            Assert.isTrue(orderItem.getSkuNum()<productSku.getStockNum(),"库存不足,下单失败");
            //插入每个订单详情(也就是订单里的订单项)到数据库
            orderItemMapper.insertOrderItem(orderItem);
        }

        //插入订单日志信息 order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.save(orderLog);
        //清空当前用户下单的购物车内容  (cart feign 调用)
        cartFeignClient.deleteCheckedCart();
        return orderInfoId;
    }

    @Override
    public TradeVo buy(Long skuId) {
        //需要获取购物车里的信息,封装到tradeVo里的集合里
        ProductSku productSku = productFeignClient.getSkuById(skuId);

        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);

        // 计算总金额  大数的计算方式.
        BigDecimal totalAmount = new BigDecimal(0);
        totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        return tradeVo;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectOrderInfoById(orderId);
        return orderInfo;
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        OrderInfo orderInfo= orderInfoMapper.getOrderInfoByOrderNo(orderNo);
        List<OrderItem> orderItemList= orderItemMapper.selectOrderItemByOrderId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public PageInfo<OrderInfo> getOrderListByPage(int page, int limit, Integer orderStatus) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        PageHelper.startPage(page,limit);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectOrderListByPage(orderStatus,userInfo.getId());
        PageInfo<OrderInfo> pageInfo = new PageInfo<>(orderInfoList);
        return pageInfo;
    }

    @Override
    public void updateOrderStatus(String orderNo, int orderStatus) {
        orderInfoMapper.updateOrderStatus(orderNo,orderStatus);
    }
}
